package com.yc.navy.goods.websocket;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@Component
@ServerEndpoint("/chat/{id}/{name}")
public class ChatServerSocket {
	private static int onlineCount = 0;
	private static ConcurrentMap<String, ChatServerSocket> webSocketMap = new ConcurrentHashMap<>();
	private Session session;
	private String id;	
	private String name;
	
	@OnOpen
	public void OnOpen(Session session, @PathParam("id") String id, @PathParam("name") String name) {
		System.out.println("gggggg");
		this.session = session;
		this.id = id;
		this.name = name;
		
		if(this.name.length() > 10) {
			try {
				this.name = URLDecoder.decode(name, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		if(webSocketMap.containsKey(id)) {
			webSocketMap.remove(id);
		}else {
			addOnLineCount();
		}
		webSocketMap.put(id, this);
		System.out.println(LocalDateTime.now() + " 用户" + name + " 连接上来了,当前在线用户人数:" + onlineCount + "...");
		String str = getInfo();
		for(ChatServerSocket wss : webSocketMap.values()) {
			wss.sendMessage(str);
		}
	}

	private String getInfo() {
		JSONObject obj = new JSONObject();
		obj.put("code", "101");
		String str = "";
		for(ChatServerSocket wss : webSocketMap.values()) {
			str += wss.id + "-" + wss.name + ";";
		}
		obj.put("data", str);
		return obj.toJSONString();
	}

	/**
	 * 发送消息的方法
	 * @param string
	 */
	public void sendMessage(String msg) {
		try {
			session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@OnClose
	public void Onclose() {
		webSocketMap.remove(id);
		subOnLineCount();
		System.out.println(LocalDateTime.now() + " 用户" + name + " 下线了,当前在线用户人数:" + onlineCount + "...");
	}
	
	@OnMessage
	public void OnMessage(String msg, Session session) {
		System.out.println(LocalDateTime.now() + "收到来自" + name + " 用户发送的消息" + msg);
		if(msg.startsWith("data:")) {	// 说明是聊天数据,格式: 接收者#消息内容
			msg = msg.replaceFirst("data:", "");
			String[] temp = msg.split("#");
			if("all".equals(temp[0])) {	// 说明是群发
				for(String key : webSocketMap.keySet()) {	// 群发   for(ChatServerSocket wss : webSocketMap.values()) {	
					if(key == this.id) {
						continue;
					}
					webSocketMap.get(key).sendMessage(getMsgInfo(temp[1]));
					//wss.sendMessage(getMsgInfo(temp[1]));
				}
				return;
			}
			
			ChatServerSocket css = webSocketMap.getOrDefault(temp[0], null);
			if(css != null) {
				css.sendMessage(getMsgInfo(temp[1]));
			}
			return;
		}
	}
	
	private String getMsgInfo(String str) {
		JSONObject obj = new JSONObject();
		obj.put("code", "103");
		obj.put("data", str);
		obj.put("name", name);
		obj.put("id", id);
		return obj.toJSONString();
	}

	@OnError
	public void OnError(Session session, Throwable error) {
		new RuntimeException(error);
	}
	
	/**
	 * 根据用户aid获取登录信息
	 * @param aid
	 * @return
	 */
	public static ChatServerSocket getWebServerSocket(String id) {
		if(webSocketMap.isEmpty()) {
			return null;
		}
		
		return webSocketMap.get(id);
	}
	
	private void subOnLineCount() {
		-- onlineCount;
		
	}

	private void addOnLineCount() {
		++ onlineCount;
	}
	
	public static int getOnLineCount() {
		return onlineCount;
	}
}
